import axios, { AxiosError } from 'axios';
import { ShowLoading, HidenLoading } from './loading';
import storage from './storage';
import { Result } from '@/types';
import { message } from '@/utils/AntdGlobal';

const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 80000,
  timeoutErrorMessage: '请求超时，请稍后再试',
  withCredentials: true,
  headers: {
    icode: '4C9A49C226B59CD8'
  }
});

instance.interceptors.request.use(
  config => {
    if (config.showLoading) ShowLoading();
    const token = storage.get('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token} `;
    }
    if (import.meta.env.VITE_MOCK === 'true') {
      config.baseURL = import.meta.env.VITE_MOCK_API;
    } else {
      config.baseURL = import.meta.env.VITE_BASE_API;
    }
    return {
      ...config
    };
  },
  (error: AxiosError) => {
    message.error(error.message);
    HidenLoading();
    return Promise.reject(error.message);
  }
);

instance.interceptors.response.use(
  response => {
    const data: Result = response.data;
    HidenLoading();
    if (response.config.responseType === 'blob') {
      return response;
    }
    if (data.code === 500001) {
      message.error(data.msg);
      storage.remove('token');
      location.href = '/login';
    } else if (data.code != 0) {
      if (response.config.showError === false) {
        return Promise.resolve(data);
      } else {
        message.error(data.msg);
        return Promise.reject(data);
      }
    }
    return data.data;
  },
  (error: AxiosError) => {
    HidenLoading();
    return Promise.reject(error);
  }
);

interface Iconfig {
  showLoading: boolean;
  showError: boolean;
}

export default {
  get<T>(
    url: string,
    params?: object,
    options: Iconfig = { showError: true, showLoading: true }
  ): Promise<T> {
    return instance.get(url, { params, ...options });
  },

  post<T>(
    url: string,
    params?: object,
    options: Iconfig = { showError: true, showLoading: true }
  ): Promise<T> {
    return instance.post(url, params, options);
  },

  downLoadFile(url: string, data: any, fileName = 'fileName.xlsx') {
    instance({
      url,
      data,
      method: 'post',
      responseType: 'blob'
    }).then(response => {
      const blob = new Blob([response.data], {
        type: response.data.type
      });
      const name = response.headers['file-name'] || fileName; // 文件名称和后端约定放在请求头
      const link = document.createElement('a');
      link.download = decodeURIComponent(name);
      link.href = URL.createObjectURL(blob); // 把file对象或者blob转换为连接
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(link.href); // 释放URL防止内存泄漏
    });
  }
};
